package kxfang.com.main.ui;

import android.content.Intent;
import android.net.http.SslError;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;


import kxfang.com.base.activity.MvvmBaseActivity;
import kxfang.com.base.utils.GsonUtils;
import kxfang.com.base.viewmodel.IMvvmBaseViewModel;
import kxfang.com.common.config.HttpConfig;
import kxfang.com.common.dialog.WaitDialog;
import kxfang.com.common.parameter.NewSharePar;
import kxfang.com.common.router.RoutHub;
import kxfang.com.common.utils.HawkUtil;
import kxfang.com.common.utils.MyUtils;
import kxfang.com.common.utils.RouterUtils;
import kxfang.com.common.utils.StatusBarUtil;
import kxfang.com.http.EasyHttp;
import kxfang.com.http.callback.SimpleCallBack;
import kxfang.com.http.exception.ApiException;
import kxfang.com.main.R;
import kxfang.com.main.databinding.MainWebviewLayoutBinding;

import static kxfang.com.common.router.RoutHub.COUPONS_MAIN;
import static kxfang.com.common.router.RoutHub.WEB_MAIN;

/**
 * Created by ZJ
 * on 2020/5/14
 * Class Content 跳转其他链接的通用web页面
 */
@Route(path = WEB_MAIN)
public class OtherWebVIewActivity extends MvvmBaseActivity<MainWebviewLayoutBinding, IMvvmBaseViewModel> {

    private WebSettings webSettings;
    private WaitDialog.Builder waitDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setTopActivityView(this, viewDataBinding.topView);
        waitDialog =new WaitDialog.Builder(this);
        waitDialog.setMessage("加载中").show();
        if (!TextUtils.isEmpty(getIntent().getStringExtra("url"))){
            initView(getIntent().getStringExtra("url"));
        }else {
            initView(getIntent().getExtras().getString("url"));
        }
        if(!TextUtils.isEmpty(getIntent().getStringExtra("title"))){
            viewDataBinding.topContent.setText(getIntent().getStringExtra("title"));
        }else {
            viewDataBinding.topContent.setText(getIntent().getExtras().getString("title"));
        }

        viewDataBinding.webBack.setOnClickListener(v -> finish());
    }

    @Override
    protected IMvvmBaseViewModel getViewModel() {
        return null;
    }

    @Override
    protected int getBindingVariable() {
        return 0;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.main_webview_layout;
    }

    @Override
    protected void onRetryBtnClick() {

    }

    private void initView(String url) {
        webSettings = viewDataBinding.webView.getSettings();
        viewDataBinding.webView.clearCache(true);
        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        //设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        //缩放操作
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件
//        webView.addJavascriptInterface(new test(this), "test");
        viewDataBinding.webView.addJavascriptInterface(this,"test");
        viewDataBinding.webView.loadUrl(url);
        viewDataBinding.webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                viewDataBinding.webView.loadUrl(url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                waitDialog.dismiss();
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//                    webView.getSettings()
//                            .setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
//                }
                // 接受所有网站的证书
                handler.proceed();
            }
        });
    }
    @JavascriptInterface
    public void userLogin(){
        if (HawkUtil.getUserId() == null){
            ToastUtils.showShort("您还没有登录");
            return;
        }
    }
    @JavascriptInterface
    public void calling(String tel){
        MyUtils.callPhone(OtherWebVIewActivity.this,tel);
    }

    @JavascriptInterface
    public void hisFb(String param){
        try {
            JSONObject jsonObject=new JSONObject(param);
            Bundle bundle = new Bundle();
            bundle.putString("userid",jsonObject.getString("userId"));
            RouterUtils.navigate(RoutHub.IT_FIND, bundle, OtherWebVIewActivity.this);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @JavascriptInterface
    public void dianzan(String param){
        NewSharePar newSharePar = new Gson().fromJson(param,NewSharePar.class);
        EasyHttp.post(HttpConfig.getNewShare)
                .cacheKey(HttpConfig.getNewShare)
                .upJson(GsonUtils.toJson(newSharePar))
                .execute(new SimpleCallBack<Boolean>() {
                    @Override
                    public void onSuccess(Boolean aBoolean) {

                    }

                    @Override
                    public void onError(ApiException e) {

                    }

                    @Override
                    public void onCompleted() {

                    }
                });

    }

    //分享参数
    @JavascriptInterface
    public void shares(String param){
        OtherWebVIewActivity.this.runOnUiThread(new Runnable() {
            public void run() {
                try {
                    JSONObject jsonObject = new JSONObject(param);
                    String url=jsonObject.getString("url");
                   String title=jsonObject.getString("Title");
                    String content=jsonObject.getString("shareDes");
                    String img=jsonObject.getString("Img");

                    MyUtils.shareDialog(OtherWebVIewActivity.this,url,title,content,img);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
